﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.SysCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;

namespace RBAC_Uthorization.API.Application.CommandHandlers.SysHanlder
{
    public class SysCreateCommandHandlers : IRequestHandler<SysCreateCommand, ApiResult<int>>
    {
        private readonly ISysRepository _sysRepository;
        private readonly ILogger<SysCreateCommandHandlers> _logger;
        private readonly IMapper _mapper;

        public SysCreateCommandHandlers(ISysRepository sysRepository, ILogger<SysCreateCommandHandlers> logger, IMapper mapper)
        {
            _sysRepository = sysRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(SysCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var existingSys = await _sysRepository.GetAllAsunc(m => m.Name == request.dto.Name);
                if (existingSys.Any())
                {
                    return new ApiResult<int>(ResultCode.Error, "系统名已存在");
                }
                var map = _mapper.Map<sys_System>(request.dto);
                map.create_by = request.CreateName;
                map.create_date = DateTime.UtcNow;
                var result = await _sysRepository.AddAsync(map);
                _logger.LogInformation($"创建人：{request.CreateName},创建系统：{map.Name},系统id：{map.Id}");
                return new ApiResult<int>() { Data = result };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建系统时发生错误");
                return new ApiResult<int>(ResultCode.Fail, "创建系统失败");
            }
        }
    }
}
